import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { jwtConstants } from "../../utils/constants";
import { ConfigService } from '@nestjs/config';
import { RedisService } from 'src/db/redis/redis.service';
import { UserService } from 'src/service/user/user.service'
export interface JwtPayload {
    name: string;
    id: string | number;
    phone: string
}


@Injectable()
// 验证请求头中的token
export class JwtAuthStrategy extends PassportStrategy(Strategy, "jwt") {
    constructor(
        private readonly configService: ConfigService,
        private redisService: RedisService,
        private userService: UserService
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: false,
            secretOrKey: jwtConstants.secret,
            // secretOrKey: configService.get('JWT_SECRET') ?? 'secret',
            passReqToCallback: true,    // 注意点 ②
        })
    }
    // JWT验证 - Step 4: 被守卫调用
    async validate(req, payload: JwtPayload) {
        // 验证通过后，payload会作为参数传递给validate()方法

        const token = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
        let cacheToken = await this.redisService.get(`${payload.id}&${payload.phone}&${payload.name}`)
        if (!cacheToken) {
            throw new UnauthorizedException('token 不存在')
        }
        if (token != cacheToken) {
            throw new UnauthorizedException('token不正确');
        }
        let exitUser = await this.userService.getUser(payload)
        if (!exitUser) {
            throw new UnauthorizedException('token 不正确')
        }
        return {
            ...payload
        }
    }
}
